﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Text.RegularExpressions;

namespace Studio.Foundation.Text
{
    public class StringUtilities
    {

        public static string Cut(string source, string prefix, string ending)
        {
            int index = source.IndexOf(prefix);
            if (index >= 0)
            {
                source = source.Substring(index + prefix.Length);
                index = source.IndexOf(ending);
                if (index >= 0) source = source.Substring(0, index);
            }
            return source;
        }

        /// <summary>
        /// Method to make sure that user's inputs are not malicious
        /// </summary>
        /// <param name="text">User's Input</param>
        /// <param name="maxLength">Maximum length of input</param>
        /// <returns>The cleaned up version of the input</returns>
        public static string InputText(string text, int maxLength)
        {
            text = text.Trim();
            if (string.IsNullOrEmpty(text))
                return string.Empty;
            if (text.Length > maxLength)
                text = text.Substring(0, maxLength);
            text = Regex.Replace(text, "[\\s]{2,}", " ");	//two or more spaces
            text = Regex.Replace(text, "(<[b|B][r|R]/*>)+|(<[p|P](.|\\n)*?>)", "\n");	//<br>
            text = Regex.Replace(text, "(\\s*&[n|N][b|B][s|S][p|P];\\s*)+", " ");	//&nbsp;
            text = Regex.Replace(text, "<(.|\\n)*?>", string.Empty);	//any other tags
            text = text.Replace("'", "''");
            return text;
        }

        /// <summary>
        /// Method to check whether input has other characters than numbers
        /// </summary>
        public static string CleanNonWord(string text)
        {
            return Regex.Replace(text, "\\W", "");
        }

        /// <summary>
        /// 将传来的字符串中的html标记替换。
        /// </summary>
        /// <param name="text"></param>
        /// <returns></returns>
        public static string EncodeHtmlText(string text)
        {
            string s;
            s = text.Replace("<", "&1htag1&");
            s = s.Replace(">", "&2htag2&");

            return s;

        }

        /// <summary>
        /// 将传来的字符串中的html标记替换。
        /// </summary>
        /// <param name="text"></param>
        /// <returns></returns>
        public static string DecodeHtmlText(string text)
        {
            string s;
            s = text.Replace("&1htag1&", "<");
            s = s.Replace("&2htag2&", ">");

            return s;

        }


    }
}
